package com.pan.insist.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pan.insist.base.BaseController;
import com.pan.insist.bean.LayuiTreeNode;
import com.pan.insist.constant.CommonConstant;
import com.pan.insist.model.MenuModel;
import com.pan.insist.model.UserModel;
import com.pan.insist.service.MenuService;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author kaiji
 */
@Log4j2
@Controller
@RequestMapping("/page")
public class PageController extends BaseController {

    @Resource
    private MenuService menuService;

    @GetMapping("")
    public String index(ModelMap modelMap) {
        UserModel userModel = (UserModel) SecurityUtils.getSubject().getPrincipal();
        log.info("principal对象: {}", userModel);
        boolean match = SecurityUtils.getSubject().hasRole(CommonConstant.ADMIN);
        List<MenuModel> menuModelAllList;
        if (match) {
            QueryWrapper<MenuModel> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(MenuModel::getMenu, CommonConstant.MAGIC_VALUE_ONE)
                    .orderByDesc(MenuModel::getOrderNum);
            menuModelAllList = menuService.list(queryWrapper);
        } else {
            menuModelAllList = menuService.getPageMainMenuByUser(userModel.getId());
        }

        modelMap.put("layuiTreeNodes", menu2Layui(menuModelAllList));
        return "page/main";
    }

    /**
     * 菜单对象转成LayUi树对象
     *
     * @param menuModelAllList
     *      所有的菜单对象列表
     * @return  LayUi树对象
     */
    private List<LayuiTreeNode> menu2Layui(List<MenuModel> menuModelAllList) {
        List<MenuModel> menuModelTops = menuModelAllList.stream()
                .filter(menuModel -> StringUtils.equals(menuModel.getPid(), CommonConstant.MAGIC_VALUE_STR_ZERO))
                .collect(Collectors.toList());
        return Optional.of(fun(menuModelAllList, menuModelTops)).get();
        // if (menuModelTops.size() <= 0) {
        //     // return REDIRECT+"notRole";
        //     return null;
        // }
        // return fun(menuModelAllList, menuModelTops);
    }

    /**
     * 递归循环 - 获取LayUiTreeNode
     *
     * @param menuModelAllList
     *      所有的菜单列表
     * @param menuModelTops
     *      顶级菜单列表
     * @return  获取LayUiTreeNode
     */
    private List<LayuiTreeNode> fun(List<MenuModel> menuModelAllList, List<MenuModel> menuModelTops) {
        List<LayuiTreeNode> nodeList = new ArrayList<>();
        for (MenuModel menuModel : menuModelTops) {
            LayuiTreeNode node = new LayuiTreeNode();
            node.setTitle(menuModel.getName());
            node.setId(menuModel.getId());
            node.setField(menuModel.getId());
            node.setHref(menuModel.getUrl());
            node.setIcon(Optional.ofNullable(menuModel.getIcon()).orElse(null));
            List<MenuModel> childrenList = menuModelAllList.stream()
                    .filter(children -> StringUtils.equals(children.getPid(), menuModel.getId()))
                    .sorted(Comparator.comparing(MenuModel::getOrderNum))
                    .collect(Collectors.toList());
            if (childrenList.size() > 0) {
                node.setChildren(fun(menuModelAllList, childrenList));
            }
            nodeList.add(node);
        }

        return nodeList;
    }
}
